package cn.chendd.itext;

import com.itextpdf.text.*;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.*;

import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 简单生成Pdf测试类
 *
 * @author chendd
 * @date 2022/7/6 22:26
 */
public class TestWatermark {

    public static void main(String[] args) throws Exception {
        Document doc = null;
        PdfWriter writer = null;
        File file = null;
        try {
            file = File.createTempFile("用户数据_", ".pdf");
            List<User> dataList = createDataList();
            doc = new Document(PageSize.A4, 10, 10, 10, 10);
            writer = PdfWriter.getInstance(doc, new FileOutputStream(file));
            BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
            Font headerFont = new Font(baseFont, 12F, Font.BOLD);//标题
            Font titleFont = new Font(baseFont, 10F, Font.BOLD);//列明
            Font contentFont = new Font(baseFont, 8F, Font.NORMAL);//内容
            doc.open();
            //主题信息
            doc.addAuthor("chendd");
            doc.addTitle("用户数据");
            doc.addSubject("家有儿女");
            doc.addKeywords("https://www.chendd.cn");
            //数据表格
            addTableContent(doc, headerFont, titleFont, contentFont, dataList);
            //TODO 使用PdfWriter生成pdf时添加水印
            //addWatermark(writer , baseFont);
            System.out.println("文档创建完毕：" + file.getAbsolutePath());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (doc != null) {
                doc.close();
            }
            if (writer != null) {
                writer.close();
            }
            if (doc != null) {
                doc.close();
            }
        }
        //TODO 生成pdf文件后，再读取pdf文件增加水印
        PdfReader reader = new PdfReader(new FileInputStream(file));
        // 加完水印的文件
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(file));
        // 设置字体
        BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
        // 设置透明度
        PdfGState gs = new PdfGState();
        // pdf页数
        int pageCount = reader.getNumberOfPages() + 1;
        // 循环对每页插入水印
        for (int i = 1; i < pageCount; i++)
        {
            addWatermarks(stamper , gs , baseFont , i);
        }
        stamper.close();
        reader.close();
    }

    private static void addWatermarks(PdfStamper stamper , PdfGState gs , BaseFont baseFont , int page) {
        // 水印的起始
        PdfContentByte content = stamper.getOverContent(page);
        gs.setFillOpacity(0.5f);
        content.setGState(gs);
        // 开始
        content.beginText();
        // 设置颜色 默认为黑色
        content.setColorFill(BaseColor.LIGHT_GRAY);
        // 设置字体及字号
        content.setFontAndSize(baseFont, 20);
        // 开始写入水印
        //循环追加生产水印
        for (int j = 0 ; j < 6 ; j++) {
            int y = j * 150 + 15;
            for (int i = 0 ; i < 4 ; i++) {
                int x = i * 50 * 3 + 50;
                content.showTextAligned(Element.ALIGN_BASELINE, "内部资料", x, y, 45);
            }
        }
        content.endText();
    }

    private static void addWatermark(PdfWriter writer , BaseFont baseFont) {
        PdfContentByte water = writer.getDirectContentUnder();
        // 开始设置水印
        water.beginText();
        // 设置水印透明度
        PdfGState gs = new PdfGState();
        // 设置笔触字体不透明度为0.2f
        gs.setStrokeOpacity(0.4f);
        gs.setFillOpacity(0.4f);
        try {
            /*Image image = Image.getInstance("d:/tomatocc.jpg");
            // 设置坐标 绝对位置 X Y
            image.setAbsolutePosition(200, 300);
            // 设置旋转弧度
            image.setRotation(30);// 旋转 弧度
            // 设置旋转角度
            image.setRotationDegrees(45);// 旋转 角度
            // 设置等比缩放
            image.scalePercent(90);// 依照比例缩放
            // image.scaleAbsolute(200,100);//自定义大小
            // 添加水印图片
            water.addImage(image);*/
            // 设置颜色 默认为黑色
            water.setColorFill(BaseColor.LIGHT_GRAY);
            // 设置透明度
            water.setGState(gs);
            water.setFontAndSize(baseFont , 38f);
            water.showTextAlignedKerned(Element.ALIGN_BASELINE , "内部资料，禁止外传" , 180 , 340 , 45);
            //结束设置
            water.endText();
            water.stroke();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //添加主信息列表的相关表格数据
    private static void addTableContent(Document doc, Font headerFont, Font titleFont, Font contentFont, List<User> dataList) throws Exception {
        PdfPTable table = new PdfPTable(7);// 6列的表格
        table.setWidths(new int[]{50, 100, 100, 100, 100, 150, 150});
        table.setWidthPercentage(100);//百分比的宽度
        Image image = Image.getInstance("d:/logo.jpg");
        PdfPCell imageCell = new PdfPCell(new Phrase(new Chunk(image, 0, -40,false)));
        PdfPCell titleCell = new PdfPCell(new Paragraph(new Chunk("用户信息表", headerFont)
                .setLocalDestination("用户信息表_link")));
        titleCell.setMinimumHeight(45f);
        titleCell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
        titleCell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
        titleCell.setColspan(6);
        PdfPRow titleRow = new PdfPRow(new PdfPCell[]{imageCell, titleCell, titleCell, titleCell, titleCell, titleCell, titleCell});
        table.getRows().add(titleRow);
        //添加字段名称行
        PdfPRow headerRow = new PdfPRow(new PdfPCell[]{
                new SimplePdfCell("序号", titleFont, 18F).getCenterCell(),
                new SimplePdfCell("名称", titleFont, 18F).getCenterCell(),
                new SimplePdfCell("性别", titleFont, 18F).getCenterCell(),
                new SimplePdfCell("年龄", titleFont, 18F).getCenterCell(),
                new SimplePdfCell("身份证号码", titleFont, 18F).getCenterCell(),
                new SimplePdfCell("联系地址", titleFont, 18F).getCenterCell(),
                new SimplePdfCell("操作", titleFont, 18F).getCenterCell()
        });
        table.getRows().add(headerRow);
        //超链接字体样式
        Font linkFont = new Font(contentFont.getBaseFont(), contentFont.getSize());
        linkFont.setColor(42, 0, 255);//蓝色
        linkFont.setStyle(Font.UNDERLINE);//下划线
        for (int i = 0, size = dataList.size(); i < size; i++) {
            User user = dataList.get(i);
            PdfPRow dataRow = new PdfPRow(new PdfPCell[]{
                    new SimplePdfCell(user.getUserId().toString(), contentFont, 18F).getCenterCell(),
                    new SimplePdfCell(user.getUserName(), contentFont, 18F).getLeftCell(),
                    new SimplePdfCell(user.getSex(), contentFont, 18F).getCenterCell(),
                    new SimplePdfCell(user.getAge().toString(), contentFont, 18F).getCenterCell(),
                    new SimplePdfCell(user.getIdNumber(), contentFont, 18F).getCenterCell(),
                    new SimplePdfCell(user.getAddress(), contentFont, 18F).getLeftCell(),
                    new SimplePdfCell(new Paragraph(new Chunk("回到顶部", linkFont).setLocalGoto("用户信息表_link")),
                            contentFont, 18F).getCenterCell()
            });
            table.getRows().add(dataRow);
        }
        doc.add(table);
        doc.newPage();
    }

    /**
     * 构造100条数据
     * return数据列表
     */
    private static List<User> createDataList() {
        List<User> dataList = new ArrayList<User>();
        for (int i = 1; i <= 100; i++) {
            User user = new User();
            dataList.add(user);
            user.setUserId(i);
            boolean flag = i % 2 == 0;
            user.setUserName(flag ? "chenzy" : "chenyt");
            user.setSex(flag ? "女" : "男");
            user.setAge((short) (flag ? 6 : 1));
            user.setIdNumber(flag ? "420682" : "420115");
            user.setAddress(flag ? "湖北省老河口市" : "湖北省武汉市");
        }
        return dataList;
    }
}
